package com.meida.student.app.scholartyrant.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.UpdateInterceptor;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.client.entity.BusScholartyrant;
import com.meida.module.bus.client.enums.ScholarTyrantCheckStateEnum;
import com.meida.module.bus.provider.service.BusScholartyrantService;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ScholarTyrantUpdateHandler implements UpdateInterceptor<BusScholartyrant> {

    @Autowired
    private BusScholartyrantService busScholartyrantService;

    @Autowired
    private AppUserService appUserService;

    @Override
    public ResultBody validate(CriteriaUpdate cu, EntityMap params) {
        Long userId = OpenHelper.getUserId();
        System.out.println(userId);
        Long num = busScholartyrantService.countNumByUserId(userId);
        if (num == 0) {
            return ResultBody.failed("后台未设置学霸身份");
        }
        return ResultBody.ok();
    }

    @Override
    public void prepare(CriteriaUpdate cu, EntityMap params, BusScholartyrant busScholartyrant) {
        Long userId = OpenHelper.getUserId();
        cu.eq("scholartyrantId", userId);
        busScholartyrant.setState(ScholarTyrantCheckStateEnum.waitCheck.getValue());
    }

    @Override
    public void complete(CriteriaUpdate cu, EntityMap params, BusScholartyrant busScholartyrant) {
        Long userId = OpenHelper.getUserId();
        String userName = params.get("userName");
        AppUser appUser = appUserService.getById(userId);
        if (FlymeUtils.isNotEmpty(appUser)) {
            appUser.setUserName(userName);
            appUserService.updateById(appUser);
        }
    }
}
